import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

public class PaperSelection {
    private final ConcurrentHashMap<Paper, Student> selections = new ConcurrentHashMap<>();

    public synchronized boolean tryAddAll(Student student, List<Paper> papers) {
        // 检查学生是否已选过
        if (selections.values().contains(student)) {
            return false;
        }

        // 检查所有论文是否可用
        for (Paper p : papers) {
            if (selections.containsKey(p)) {
                return false;
            }
        }

        // 原子性添加
        for (Paper p : papers) {
            selections.put(p, student);
        }
        return true;
    }

    public boolean isSelected(Paper paper) {
        return selections.containsKey(paper);
    }

    public Map<Paper, Student> getSelections() {
        return new HashMap<>(selections);
    }

    @Override
    public String toString() {
        return selections.entrySet().stream()
                .map(e -> e.getKey() + " selected by " + e.getValue().getName())
                .collect(Collectors.joining("\n"));
    }

    public void accept(PaperSelectionVisitor visitor) {
        visitor.visit(this);
    }
}